package com.i360day.redis.configuration.manager;

import org.springframework.data.redis.connection.DefaultStringRedisConnection;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.serializer.RedisSerializer;

import java.util.concurrent.TimeUnit;

public class RedisCacheManageTemplate extends RedisTemplate<String, Object> {


    public RedisCacheManageTemplate() {
        setKeySerializer(RedisSerializer.string());
        setHashKeySerializer(RedisSerializer.string());
    }

    /**
     * Constructs a new <code>StringRedisTemplate</code> instance ready to be used.
     *
     * @param connectionFactory connection factory for creating new connections
     */
    public RedisCacheManageTemplate(RedisConnectionFactory connectionFactory) {
        this();
        setConnectionFactory(connectionFactory);
        afterPropertiesSet();
    }

    protected RedisConnection preProcessConnection(RedisConnection connection, boolean existingConnection) {
        return new DefaultStringRedisConnection(connection);
    }


    public void setIfPresent(String key, Object value) {
        ValueOperations<String, Object> cacheValueOperations = super.opsForValue();
        Object obj = cacheValueOperations.get(key);
        if (obj == null) {
            cacheValueOperations.set(key, value);
        }
    }

    public void setIfPresent(String key, Object value, long timeout, TimeUnit unit) {
        ValueOperations<String, Object> cacheValueOperations = super.opsForValue();
        Object obj = cacheValueOperations.get(key);
        if (obj == null) {
            cacheValueOperations.set(key, value, timeout, unit);
        }
    }

}
